package com.shx.bill.controller;

import com.shx.bill.dao.ProviderDao;
import com.shx.bill.entities.Provider;
import com.shx.bill.mapper.ProviderMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@Controller
public class ProviderController {

    @Autowired
    private ProviderDao dao;

    @Autowired
    private ProviderMapper providerMapper;


    @GetMapping(value = "/provider/goToAdd")
    public String goToAddProviderPage() {
        return "provider/add";
    }

    @GetMapping(value = "/provider/providerList")
    public String list(Map<String, Object> map, Provider provider) {

        map.put("providers", providerMapper.getProviderList(provider));
        map.put("keyword", provider.getProviderName());
        return "provider/list";
    }

    @GetMapping(value = "/provider/{pid}")
    public String viewDetail(@PathVariable("pid") Integer pid,
                             @RequestParam(value = "type", defaultValue = "view") String type,
                             Map<String, Object> map) {
        map.put("provider", providerMapper.getProviderByPid(pid));

        if ("update".equals(type)) {
            return "provider/update";
        } else {
            return "provider/view";
        }
    }

    @PutMapping(value = "/provider")
    public String update(Provider provider) {
//        dao.save(provider);
        providerMapper.updateProvider(provider);
        return "redirect:/provider/providerList";
    }

    @PostMapping(value = "/provider")
    public String addProvider(Provider provider) {
//        dao.save(provider);
        providerMapper.addProvider(provider);
        return "redirect:/provider/providerList";
    }

    @DeleteMapping(value = "/provider/{pid}")
    public String deleteProvider(@PathVariable("pid") Integer pid) {
//        dao.delete(pid);
        providerMapper.deleteProvider(pid);
        return "redirect:/provider/providerList";
    }

}
